package com.yhb.service.impl;

import com.yhb.conf.ResultCode;
import com.yhb.dao.OrderMapper;
import com.yhb.model.Good;
import com.yhb.model.Order;
import com.yhb.model.User;
import com.yhb.service.*;
import com.yhb.utils.StringUtils;
import lombok.extern.log4j.Log4j;
import lombok.var;
import me.edzh.spring.bootstrap.utils.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Log4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private AppPayService appPayService;

    @Autowired
    private GoodService goodService;

    @Autowired
    private UserService userService;

    @Autowired
    private SplittingService splittingService;

    @Override
    public Order create(Order order) {
        var good = goodService.getById(order.getGoodId());
        if (good == null) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数不合法");
        }

        if (order.getGoodCount() <= 0L) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数不合法");
        }

        User user = userService.getUser(order.getUserId());
        if (good.getType() == Good.Type.PRIME && user.isModifiableVipType()) { // 临时vip或普通会员企图购买皇冠
            throw new ServiceException(ResultCode.ERROR_TOAST_ERR, "请先购买vip");
        }

        order.setAmount(good.getPrice().multiply(BigDecimal.valueOf(order.getGoodCount())));
        order.setGoodName(good.getName());
        order.setVipDays(good.getDays() * order.getGoodCount());
        order.setGoodAlbum(good.getAlbumPic());
        order.setGoodType(good.getType());

        var address = addressService.addressById(order.getAddressId());
        if (address == null || !address.getUserId().equals(order.getUserId())) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数不合法");
        }
        order.setAddressName(address.getName());
        order.setAddressMobile(address.getMobile());
        order.setAddressArea(address.getProvince() + ";" +  address.getCity() + ";" + address.getDistrict());
        order.setAddress(address.getAddress());

        order.setCreateTime(new Date());
        orderMapper.createOrder(order);
        return order;
    }

    @Override
    public void modify(Order order) {
        orderMapper.modifyOrder(order);
    }

    @Override
    public void modify(Order order, String userId) {
        var o = getById(order.getId());
        if (!o.getUserId().equals(userId)) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数错误");
        }

        orderMapper.modifyOrder(o);
    }

    @Override
    public Order getById(String orderId) {
        return orderMapper.getOrder(orderId);
    }

    @Override
    public Order getById(String orderId, String userId) {
        var o = getById(orderId);
        if (!o.getUserId().equals(userId)) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数错误");
        }
        return o;
    }

    @Override
    @Transactional
    public void onOrderPurchased(String tradeNo) {
        Order order = orderMapper.getOrderByTradeNo(tradeNo);
        if (order.getStatus() != Order.Status.COMMITTED) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "状态错误");
        }

        User user = userService.getUser(order.getUserId());
        User.VipType vipType = User.VipType.ORDINARY;
        if (order.getGoodType() == Good.Type.VIP) {
            userService.earnVip(user, Integer.MAX_VALUE);
            vipType = User.VipType.PAYED;
        } else if (order.getGoodType() == Good.Type.PRIME) {
            userService.earnPrimeVip(user, order.getVipDays().intValue());
            vipType = User.VipType.PRIME;
        }

        splittingService.clacActivateBonus(user, order.getAmount(), vipType);

        order.setStatus(Order.Status.PURCHASED);
        order.setPurchaseTime(new Date());
        orderMapper.modifyOrder(order);
        userService.modifyUser(user);
        userService.setUserActive(user.getId());
    }

    @Override
    public List<Order> userOrders(String userId) {
        return orderMapper.userOrders(userId);
    }

    @Override
    public List<Order> orderInRange(Date start, Date end) {
        return orderMapper.orderInRange(start, end);
    }

    @Override
    public void sendOrder(String orderId, String corpName, String deliverTradeNo) {
        var order = orderMapper.getOrder(orderId);
        var status = Optional.ofNullable(order.getStatus()).orElseThrow(() -> new ServiceException(ResultCode.ERROR_TOAST_ERR, "订单不存在"));
        if (status != Order.Status.PURCHASED) {
            throw new ServiceException(ResultCode.ERROR_TOAST_ERR, "订单状态异常");
        }

        orderMapper.modifyOrder(Order.builder()
                .id(order.getId())
                .status(Order.Status.SENT)
                .deliverCorpName(corpName)
                .deliverTradeNo(deliverTradeNo)
                .build());
    }

    @Override
    public String purchaseOrder(String orderId, String userId) {
        var order = orderMapper.getOrder(orderId);
        if (!order.getUserId().equals(userId)) {
            throw new ServiceException(ResultCode.ERROR_PARAMETER_WRONG, "参数错误");
        }

        var res = appPayService.invokePay(order.getAmount().multiply(BigDecimal.valueOf(order.getGoodCount())), "银合宝支付", order.getGoodName());
        order.setTradeNo(res.getValue1());

        orderMapper.modifyOrder(order);
        return res.getValue2();
    }
}
